<?php

namespace app\api\Service;

use app\common\library\Auth;
use app\common\library\Sms;
use think\Db;
use fast\Random;
use fast\Hashids;
use think\Config;
use think\Validate;
use think\Response;
use wxpay\WxPay;

class MasterService
{
    // 账号密码注册
    public static function register($data)
    {
        $auth = Auth::instance();
        $mobile = $data['mobile'];
        $code = $data['code'];
        $password = $data['password'];

        $username = $mobile;
        if (!$username || !$password) {
            return ['code'=>0,'msg'=>'无效参数','data'=>''];
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            return ['code'=>0,'msg'=>'手机号格式不正确','data'=>''];
        }
        $ret = Sms::check($mobile, $code, 'mregister');
//        $ret = true;
        if (!$ret) {
            return ['code'=>0,'msg'=>'验证码错误','data'=>''];
        }
        $invite = generateUniqueNumber();
        $ret = $auth->register($mobile, $password, '', $mobile, 2, ['invite'=>$invite]);
        if ($ret) {
            Sms::flush($mobile, 'register');
            $data = $auth->getUserinfo();
            return ['code'=>1,'msg'=>'注册成功','data'=>$data];
        } else {
            return ['code'=>0,'msg'=>$auth->getError(),'data'=>''];
        }
    }

    // 账号密码登录
    public static function login($data)
    {
        $auth = Auth::instance();
        $account = $data['mobile'];
        $password = $data['password'];
        if (!$account || !$password) {
            return ['code'=>0,'msg'=>'无效参数','data'=>''];
        }
        $ret = $auth->login($account, $password, 2);
        if ($ret) {
            $data = $auth->getUserinfo();
            return ['code'=>1,'msg'=>'登录成功','data'=>$data];
        } else {
            return ['code'=>0,'msg'=>$auth->getError(),'data'=>''];
        }
    }

    // 重置密码
    public static function resetpwd($data)
    {
//
        $mobile = $data['mobile'];
        $newpassword = $data['password'];
        $captcha = $data['code'];
        if (!$newpassword || !$captcha) {
            return ['code'=>0,'msg'=>'无效参数','data'=>''];
        }

        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            return ['code'=>0,'msg'=>'密码必须为6到30个字符','data'=>''];
        }

        if (!Validate::regex($mobile, "^1\d{10}$")) {
            return ['code'=>0,'msg'=>'手机号格式不正确','data'=>''];
        }
        $user = \app\common\model\User::where(['mobile' => $mobile,'group_id'=>2])->find();
        if (!$user) {
            return ['code'=>0,'msg'=>'用户信息不存在','data'=>''];
        }
        $status = $user->status;
        if ($status == 'hidden') {
            return ['code'=>0,'msg'=>'账号已锁定','data'=>''];
        }
        if($status == 'logoff'){
            return ['code'=>0,'msg'=>'账号已注销','data'=>''];
        }
        $ret = Sms::check($mobile, $captcha, 'resetpwd');
//        $ret = true;
        if (!$ret) {
            return ['code'=>0,'msg'=>'验证码错误','data'=>''];
        }
        Sms::flush($mobile, 'resetpwd');
        //模拟一次登录
//        $auth = Auth::instance();
//        $auth->direct($user->id);

        $salt = Random::alnum();
        $user->password = md5(md5($newpassword) . $salt);
        $ret = $user->save(['loginfailure' => 0, 'password' => $user->password, 'salt' => $salt]);
        if ($ret) {
            return ['code'=>1,'msg'=>'操作成功','data'=>['password' => $user->password, 'salt' => $salt]];
        } else {
            return ['code'=>1,'msg'=>'操作失败','data'=>''];
        }
    }

    // 获取个人信息
    public static function getUserInfo($data)
    {
        $auth = Auth::instance();
        $userInfo = $auth->getUserinfo();
        $userInfo['order_count'] = \app\admin\model\Order::where(['master_id'=>$auth->id,'status'=>['in',[1,2,3]]])->count();
        $userInfo['credit'] = $auth->credit;
        $userInfo['level'] = $auth->level;
        $userInfo['province_id'] = $auth->province_id;
        $userInfo['city_id'] = $auth->city_id;
        $userInfo['area_id'] = $auth->area_id;
        $userInfo['city'] = \app\admin\model\Area::where(['id'=>$auth->city_id])->value('name');
        $userInfo['coupon_number'] = \app\admin\model\CouponUser::where(['user_id'=>$auth->id,'status'=>1])->count();
        $masterRealname = \app\admin\model\MasterRealname::where(['user_id'=>$auth->id])->find();
        if($masterRealname){
            $userInfo['is_realname'] = $masterRealname['status'];
        }else{
            $userInfo['is_realname'] = 100;
        }
        $userInfo['is_sign'] = $auth->is_sign;
        $userInfo['is_online'] = $auth->is_online;
        $userInfo['is_hidden'] = 2;


        return ['code'=>1,'msg'=>'获取成功','data'=>$userInfo];
    }

    // 上线下线开关
    public static function setOnline($data)
    {
        $auth = Auth::instance();
        $user_id = $auth->id;
        $status = $data['is_online'];
        $user = \app\common\model\User::get($user_id);
        $user->is_online = $status;
        $ret = $user->save();
        if ($ret) {
            return ['code'=>1,'msg'=>'操作成功','data'=>''];
        } else {
            return ['code'=>0,'msg'=>'操作失败','data'=>''];
        }
    }

    /**
     * 积分明细
     */
    public static function getScoreList($data)
    {
        $auth = Auth::instance();
        $limit = isset($data['limit']) ? $data['limit'] : 10;
        $user_id = $auth->id;
        $list = \app\common\model\ScoreLog::where(['user_id'=>$user_id])->field('id,score,memo,FROM_UNIXTIME(createtime,"%Y-%m-%d %H:%i:%s") as createtime_text')->order('createtime DESC')->paginate($limit);

        return ['code'=>1,'msg'=>'获取成功','data'=>['score'=>$auth->score,'list'=>$list]];
    }

    /**
     * 我的优惠劵
     */
    public static function getCouponList($data)
    {
        $auth = Auth::instance();
        $user_id = $auth->id;
        $type = isset($data['type']) ? $data['type'] : '';// install-安装  repair-维修 shops-商城
        $money = isset($data['money']) ? $data['money'] : 0;
        $where['user_id'] = $user_id;
        $where['status'] = 1;

        $list = \app\admin\model\CouponUser::where($where)
            ->field('id,coupon_id,FROM_UNIXTIME(expiretime,"%Y-%m-%d %H:%i:%s") as expiretime_text')
            ->order('createtime DESC')->select();
        if($list){
            foreach ($list as &$row){
                $coupon = \app\admin\model\Coupon::where(['id'=>$row['coupon_id']])->find();
                if($type && $coupon['type'] == 1 && $money < $coupon['reduction_amount']) {
                    $row['available'] = 0;
                    $row['reason'] = '订单金额不足';
                }elseif($type == 'install' && in_array($coupon['type'],[2,3])){
                    $row['available'] = 0;
                    $row['reason'] = '订单类型不符';
                }elseif($type == 'repair' && $coupon['type'] == 3){
                    $row['available'] = 0;
                    $row['reason'] = '订单类型不符';
                }elseif($type == 'shops' && $coupon['type'] == 2){
                    $row['available'] = 0;
                    $row['reason'] = '订单类型不符';
                }else{
                    $row['available'] = 1;
                }

                $row['coupon_type'] = $coupon['type']; // 类型：1满减 2维修全免 3专属商品全额抵用
                $row['coupon_name'] = $coupon['title'];
                $row['reduction_amount'] = $coupon['reduction_amount'];
                $row['discount_amount'] = $coupon['discount_amount'];
            }
        }else{
            $list = [];
        }
        return ['code'=>1,'msg'=>'获取成功','data'=>$list];
    }

    // 重置密码
    public static function changepwd($data)
    {
//
        $mobile = $data['mobile'];
        $newpassword = $data['password'];
        $captcha = $data['code'];
        if (!$newpassword || !$captcha) {
            return ['code'=>0,'msg'=>'无效参数','data'=>''];
        }

        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            return ['code'=>0,'msg'=>'密码必须为6到30个字符','data'=>''];
        }

        if (!Validate::regex($mobile, "^1\d{10}$")) {
            return ['code'=>0,'msg'=>'手机号格式不正确','data'=>''];
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if (!$user) {
            return ['code'=>0,'msg'=>'用户信息不存在','data'=>''];
        }
        $status = $user->status;
        if ($status == 'hidden') {
            return ['code'=>0,'msg'=>'账号已锁定','data'=>''];
        }
        if($status == 'logoff'){
            return ['code'=>0,'msg'=>'账号已注销','data'=>''];
        }
//        $ret = Sms::check($mobile, $captcha, 'resetpwd');
        $ret = true;
        if (!$ret) {
            return ['code'=>0,'msg'=>'验证码错误','data'=>''];
        }
        Sms::flush($mobile, 'resetpwd');
        //模拟一次登录
        $auth = Auth::instance();
        $auth->direct($user->id);

        $salt = Random::alnum();
        $user->password = md5(md5($newpassword) . $salt);
        $ret = $user->save(['loginfailure' => 0, 'password' => $user->password, 'salt' => $salt]);
        if ($ret) {
            return ['code'=>1,'msg'=>'操作成功','data'=>''];
        } else {
            return ['code'=>1,'msg'=>'操作失败','data'=>''];
        }
    }

    // 信誉分说明
    public static function creditTips()
    {
        $auth = Auth::instance();

        $tips = Config::get('site.credit_tips');
        $price = Config::get('site.credit_price');
        $credit = $auth->credit;
        return ['code'=>1,'msg'=>'获取成功','data'=>['tips'=>$tips,'price'=>$price,'credit'=>$credit]];
    }


    // 购买信誉分
    public static function buyCredit($data)
    {
        $auth = Auth::instance();
        $user_id = $auth->id;
        $openid = $auth->openid;
        $credit = $data['credit'];
        $money = $data['money'];
        if(!$credit) return ['code'=>0,'msg'=>'购买信誉分不能为空','data'=>''];
        if(!$money) return ['code'=>0,'msg'=>'支付金额不能为空','data'=>''];
        // 检查是否绑定了微信OpenID
        if(!$openid) return ['code'=>0,'msg'=>'请先绑定微信','data'=>''];

        $price = Config::get('site.credit_price');
        $pay_price = bcmul($credit, $price);
        if($money != $pay_price) return ['code'=>0,'msg'=>'支付金额不正确','data'=>''];

        // 支付标题
        $order_no = getNewOrderNo();
        $title = "购买信誉分订单-{$order_no}";
        $pay_price = round($pay_price, 2);
        // 生成一个订单
        $order = \app\admin\model\OrderCredit::create([
            'order_no'    => $order_no,
            'user_id'    => $user_id,
            'credit' => $credit,
            'amount'   => $money,
            'payamount'   => $pay_price,
        ]);

        $type = 'wechat';
        $notifyurl = request()->domain() . '/addons/epay/index/credit_notifyx/paytype/' . $type;

        $params = [
            'amount'    => $pay_price,
            'orderid'   => $order_no,
            'type'      => $type,
            'title'     => '【'.$title.'】',
            'method'    => 'miniapp',
            'openid'    => $openid,
            'notifyurl'    => $notifyurl,
        ];
        //  $params['amount'] = 0.01;// 测试支付
        $response = WxPay::pay($params);

        return ['code'=>1,'msg'=>'操作成功','data'=>$response];
    }

    // 意见反馈
    public static function addFeedback($data)
    {
        $auth = Auth::instance();
        $user_id = $auth->id;
        $content = $data['content'];
        $annex = $data['annex'];
        if(!$content) return ['code'=>0,'msg'=>'反馈内容不能为空','data'=>''];
        if(!$annex) return ['code'=>0,'msg'=>'附件不能为空','data'=>''];

        $data = [
            'user_id' => $user_id,
            'content' => $content,
            'annex' =>$annex,
        ];
        try{
            $result = \app\admin\model\Feedback::create($data);
            Db::commit();
            if($result){
                return ['code'=>1,'msg'=>'操作成功','data'=>''];
            }else{
                return ['code'=>0,'msg'=>'操作失败','data'=>''];
            }
        }catch(\Exception $e){
            Db::rollback();
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
    }

    // 接单地址
    public static function editLocation($data)
    {
        $auth = Auth::instance();
        $user_id = $auth->id;
        $province_id = $data['province_id'];
        $city_id = $data['city_id'];
        $area_id = $data['area_id'];


        $result = \app\admin\model\User::where('id',$user_id)->update(['province_id'=>$province_id, 'city_id'=>$city_id,'area_id'=>$area_id]);
        if(!$result){
            return ['code'=>0,'msg'=>'操作失败','data'=>''];
        }
        return ['code'=>1,'msg'=>'操作成功','data'=>''];
    }

    // 消息列表
    public static function getMessageList($data)
    {
        $auth = Auth::instance();
        $user_id = $auth->id;
        $limit = isset($data['limit']) && $data['limit'] ? $data['limit'] : 10;
        $list = \app\admin\model\Massage::where('master_id',$user_id)->field('id,title,content,createtime')->order('id desc')->paginate($limit)->each(function($item, $key) use($user_id) {
            $item['createtime'] = date('Y-m-d H:i:s',$item['createtime']);
        });
        return ['code'=>1,'msg'=>'获取成功','data'=>$list];
    }






    // 修改个人信息
    public static function editUserProfile($data)
    {
        $auth = Auth::instance();
        $user = $auth->getUser();
        $nickname = $data['nickname'];
        $avatar = $data['avatar'];

        if ($nickname) $user->nickname = $nickname;
        if ($avatar) $user->avatar = $avatar;
        if(!$nickname && !$avatar) return ['code'=>0,'msg'=>'没有更新任何数据','data'=>''];
        $user->save();
        return ['code'=>1,'msg'=>'操作成功','data'=>''];
    }

    // 验证码登录
    public static function mobilelogin($data)
    {
        $auth = Auth::instance();
        $mobile = $data['mobile'];
        $captcha = $data['code'];

        if (!$mobile || !$captcha) {
            return ['code'=>0,'msg'=>'无效参数','data'=>''];
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            return ['code'=>0,'msg'=>'手机号格式不正确','data'=>''];
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            return ['code'=>0,'msg'=>'验证码错误','data'=>''];
        }

        if( isset($data['pid']) && $data['pid']){
            //实例化Hashids类
            $hashids = Hashids::instance(6,'91travel');//6为邀请码的长度，mackie为加盐密钥
            //解密
            $pid = $hashids->decode($data['pid']);
        }else{
            $pid = 0;
        }

        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status == 'hidden') {
                return ['code'=>0,'msg'=>'账号已锁定','data'=>''];
            }
            if ($user->status == 'logoff') {
                return ['code'=>0,'msg'=>'账号已注销','data'=>''];
            }
            //如果已经有账号则直接登录
            $ret = $auth->direct($user->id);
        } else {

            $invite_code = create_invite_code();

            $ret = $auth->register($mobile, '123456', '', $mobile, ['invite_code'=>$invite_code,'pid'=>$pid]);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');

            // 发邀请奖励
            if($pid){
                $bonus = Config::get('site.invite_reward');
                if($bonus){
                    $res = \app\common\model\User::bonus($bonus,$pid,'邀请注册奖励');
//                    return $res;
                }
            }

            $data = $auth->getUserinfo();
            return ['code'=>1,'msg'=>'登录成功','data'=>$data];
        } else {
            return ['code'=>0,'msg'=>$auth->getError(),'data'=>''];
        }
    }

    // 注销账号
    public static function logoff()
    {
        $auth = Auth::instance();
        $user = $auth->getUser();
        $user->status = 'logoff';
        // 修改状态
        $user->save();
        // 退出登录
        $auth->logout();
        return ['code'=>1,'msg'=>'注销成功','data'=>''];
    }

    // 退出登录
    public static function logout()
    {
        $auth = Auth::instance();
        $auth->logout();
        return ['code'=>1,'msg'=>'退出成功','data'=>''];
    }
}